<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="centerDialogVisible"
    title="请选择调入的人员"
    width="500"
    left
    :show-close="false"
  >
    <el-form
      ref="postformRef"
      :model="postformData"
      :rules="putrules"
      label-width="100px"
      class="dialog-form"
    >
      <div class="form-content">
        <div class="form-wrapper">
          <el-form-item label="当前店铺" prop="start_datea">
            <el-input
              v-model="insopname"
              disabled="true"
              show-word-limit
              clearable
              style="width: 220px"
            />
          </el-form-item>

          <el-form-item label="开始日期" prop="start_datea">
            <el-date-picker
              v-model="postformData.start_date"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>

          <el-form-item label="结束日期" prop="end_datea">
            <el-date-picker
              v-model="postformData.end_date"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="调拨人员" prop="userid_lista">
            <el-cascader
              v-model="postformData.userid_list"
              :options="departmentOptions"
              :props="cascaderProps"
              :collapse-tags="true"
              :clearable="true"
              :show-all-levels="true"
              placeholder="请选择调拨人员"
              @change="handleLeaderChange"
            />
          </el-form-item>

          <el-form-item label="店铺调出" prop="userid_lista">
            <el-cascader
              v-model="postformData.out_shop"
              placeholder="店铺调出"
              :options="departmentOptionsqw"
              :props="cascaderPropsqw"
              :show-all-levels="false"
              :collapse-tags="true"
              @change="mendiandiaochu"
              :clearable="true"
            />
          </el-form-item>
        </div>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="querendiaobo"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  ref,
  computed,
  onMounted,
  nextTick,
  reactive,
  defineProps,
  watch,
  defineEmits,
} from "vue";
import { ElTable, ElTableColumn, ElButton, ElMessage, FormInstance } from "element-plus";

import { getDepartmentList } from "@/api/department";
import { getUserInfo } from "@/api/employee";
import { posttransfer } from "@/api/schedulingManage";

import { getAttendanceGroupInfo } from "@/api/attendanceGroup";
import { getStoreInfo } from "@/api/store";

const insopname = ref("");

const centerDialogVisible = ref(false);
const props = defineProps(["falcktankun", "inshopid", "groupid"]);

const emit = defineEmits();

centerDialogVisible.value = props.falcktankun;
console.log(props.groupid);

// 监听visible变化
watch(
  () => props.falcktankun,
  async (val: boolean) => {
    centerDialogVisible.value = val;
    const res = await getStoreInfo();

    postformData.in_shop = props.inshopid;
    res.result[0].childs.forEach((item) => {
      if (item.selfid == props.inshopid) {
        insopname.value = item.shop_name;
      } else {
        insopname.value = "普通门店";
      }
    });
    if (val) {
    }
  }
);

const handleClose = () => {
  cleardata();
  emit("update:falcktankun", false);
};

const postformRef = ref<FormInstance>();

// 表单数据
const postformData = reactive<{
  userid_list?: any;
  in_shop?: any;
  out_shop?: any;
  start_date?: any;
  end_date?: any;
}>({
  userid_list: "",
  in_shop: "",
  out_shop: "",
  start_date: "",
  end_date: "",
});

const cleardata = () => {
  Object.assign(postformData, {
    userid_list: "",
    in_shop: "",
    out_shop: "",
    start_date: "",
    end_date: "",
  });
};

// 部门选项
const departmentOptions = ref([]);

const handleLeaderChange = (val: any) => {
  console.log(val);
  postformData.out_shop = val[0];
  postformData.userid_list = val[1];
};

//部门原始数据
const bumendata = ref(<Array<unknown> | any>[]);

const cascaderProps = {
  multiple: false,
  lazy: true,
  // expandTrigger: "hover",
  value: "value",
  label: "label",
  lazyLoad: async (node: any, resolve: any) => {
    console.log(node);

    const { level } = node;

    const demoid = ref("");

    if (node.label != undefined) {
      bumendata.value.forEach((item) => {
        console.log(node.label);

        if (node.label == item.name) {
          demoid.value = item.id;
        }
      });
    }

    if (level === 0) {
      // 加载部门列表
      try {
        const res = await getAttendanceGroupInfo();
        console.log("部门列表响应:", res);

        bumendata.value = res.data.info_list;

        console.log(bumendata.value);

        if (res.code === "200" && res.data?.info_list) {
          console.log(res.data.info_list);

          const departments = res.data.info_list.map((dept: any) => ({
            value: dept.id,
            label: dept.name,
            leaf: false,
          }));
          console.log("处理后的部门数据:", departments);
          resolve(departments);
        } else {
          console.error("部门数据格式错误:", res);
          resolve([]);
        }
      } catch (error) {
        console.error("获取部门列表失败:", error);
        resolve([]);
      }
    } else if (level === 1) {
      console.log(demoid.value);

      // 加载员工列表
      try {
        const deptId = demoid.value;
        console.log("正在获取部门ID为", deptId, "的员工列表");
        let employees = {};

        if (bumendata.value.length > 0) {
          console.log(bumendata.value);
          bumendata.value.forEach((item) => {
            if (deptId == item.id) {
              employees = item.user_id;
            }
          });
          console.log(employees);

          employees = employees.map((emp: any) => ({
            value: emp.userid,
            label: emp.username,
            leaf: true,
          }));
          console.log("处理后的员工数据:", employees);
          resolve(employees);
        } else {
          console.error("员工数据格式错误:", []);
          resolve([]);
        }
      } catch (error) {
        console.error("获取员工列表失败:", error);
        resolve([]);
      }
    }
  },
};

// 部门渲染数据选项
const departmentOptionsqw = ref([]);

//门店原始数据
const mendiandata = ref(<Array<unknown> | any>[]);

const cascaderPropsqw = {
  multiple: false,
  lazy: true,
  // expandTrigger: "hover",
  value: "value",
  label: "label",
  lazyLoad: async (node: any, resolve: any) => {
    const { level } = node;

    const demoid = ref("");

    if (node.label != undefined) {
      mendiandata.value.forEach((item) => {
        if (node.label == item.shop_name) {
          demoid.value = item.selfid;
        }
      });
    }

    if (level === 0) {
      // 加载部门列表
      try {
        const res = await getStoreInfo();
        console.log("门店列表响应:", res);

        mendiandata.value = res.result;

        if (res.code == "200" && res.result.length > 0) {
          const departments = res.result.map((dept: any) => ({
            value: dept.selfid,
            label: dept.shop_name,
            leaf: false,
          }));
          console.log("处理后的数据:", departments);
          resolve(departments);
        } else {
          console.error("数据格式错误:", res);
          resolve([]);
        }
      } catch (error) {
        console.error("获取列表失败:", error);
        resolve([]);
      }
    } else if (level === 1) {
      // 加载员工列表
      try {
        const mendinachilchen = ref(<Array<unknown> | any>[]);
        mendiandata.value.forEach((item: any) => {
          if (demoid.value == item.selfid) {
            mendinachilchen.value = item.childs;
          }
        });
        if (mendinachilchen.value.length > 0) {
          let employees = mendinachilchen.value.map((emp: any) => ({
            value: emp.selfid,
            label: emp.shop_name,
            leaf: true,
          }));

          const dataaa: any[] = [];
          employees.forEach((item: any) => {
            console.log(item);

            if (item.value != props.inshopid) {
              dataaa.push(item);
            } else {
              insopname.value = item.label;
            }
          });

          console.log("处理后的数据:", dataaa);
          resolve(dataaa);
        } else {
          console.error("数据格式错误:", []);
          resolve([]);
        }
      } catch (error) {
        console.error("获取列表失败:", error);
        resolve([]);
      }
    }
  },
};

const mendiandiaochu = (val: any) => {
  postformData.out_shop = val[1];
  console.log(val);
};

const querendiaobo = async () => {
  console.log(postformData);

  // if (route.query.shop_id==postformData.out_shop) {
  //   ElMessage.error("与当前店铺重合");
  //   return
  // }

  const res = await posttransfer(postformData);
  if (res.code == "200") {
    ElMessage.success("调拨成功");
    cleardata();
    emit("update:falcktankun", false);
  } else {
    ElMessage.error("调拨失败");
  }
};

onMounted(async () => {
  const res = await getStoreInfo();

  res.result[0].childs.forEach((item) => {
    if (item.selfid == props.inshopid) {
      insopname.value = item.shop_name;
    }
  });
});
</script>

<style scoped></style>
